import 'dart:async';
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutterlib/common/utils/utils.dart';
import 'package:flutterlib/pages/activity/list/activity_simple_list_widget_page.dart';
import 'package:flutterlib/pages/interest/list/interest_simple_list_widget_page.dart';
import 'package:flutterlib/pages/post/list/post_list_simple_widget_page.dart';
import 'package:flutterlib/pages/user/viewmodel/user_store.dart';
import 'package:flutterlib/widgets/bussiness/user_info_widget.dart';
import 'package:loading/indicator/ball_beat_indicator.dart';
import 'package:loading/loading.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:mobx/mobx.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tab_indicator_styler/tab_indicator_styler.dart';

import 'package:flutterlib/common/constants/constants.dart';

///个人主页页面
class Page extends StatefulWidget {
  final int userId;

  Page({Key key, this.userId})
      : super(key: key);

  @override
  PageState createState() => PageState();
}

///页面 KeepAlive ，同时支持 动画Ticker
class PageState extends State<Page>
    with SingleTickerProviderStateMixin {
  final ScrollController scrollController = ScrollController();
  RefreshController _refreshController;
  UserEntity user;
  List<Widget> data = [];
  UserStore store = UserStore();
  TabController _tabController;
  double get tabBarHeight => 56.h;
  double get expandedHeight =>
      Screens.width / 1.25 + tabBarHeight;
  final StreamController<bool> titleAnimateStreamController =
  StreamController<bool>.broadcast();

  Stream<bool> get titleAnimateStream => titleAnimateStreamController.stream;
  void enterRefresh() {
    _refreshController.requestRefresh();
  }

  @override
  void initState() {
    super.initState();
    _tabController =
    new TabController(vsync: this, length: 3);
    store.fetchUserEntity(widget.userId);
    _refreshController = RefreshController(initialRefresh: true);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    scrollController
      ..removeListener(listener)
      ..addListener(listener);
  }

  @override
  void dispose() {
    scrollController?.dispose();
    super.dispose();
  }
  void listener() {
    double triggerHeight = expandedHeight - kToolbarHeight;
    triggerHeight -= tabBarHeight;
    titleAnimateStreamController.add(scrollController.offset >= triggerHeight);
  }
  Widget appbar() {

    return StreamBuilder<bool>(
      initialData: false,
      stream: titleAnimateStream,
      builder: (BuildContext _, AsyncSnapshot<bool> data) {
        final bool shouldTitleDisplay = data.data;
        return SliverAppBar(
          brightness: shouldTitleDisplay
              ? context.themeData.brightness
              : Brightness.dark,
          expandedHeight: expandedHeight,
          elevation: 0.0,
          pinned: true,
          leading: MyBackButton(
            color:  Colors.white,
          ),
          title: AnimatedSwitcher(
            duration: kThemeChangeDuration,
            child: shouldTitleDisplay
                ? appBarTitleWidget
                : const SizedBox.shrink(),
          ),
          flexibleSpace: FlexibleSpaceBar(
            collapseMode: CollapseMode.pin,
            background: appBarBackgroundWidget,
          ),
          bottom: PreferredSize(
            preferredSize: const Size.fromHeight(48.0),
            child: Container(
              child: Container(
                width: double.infinity,
                decoration: new BoxDecoration(
                  color: QuhuiColors.miWhite, // 底色
                  shape: BoxShape.rectangle, // 默认值也是矩形
                  borderRadius: new BorderRadius.only(
                    topLeft: Radius.circular(20.0),
                    topRight: Radius.circular(20.0),
                  ), // 圆角度
                ),
                child: new TabBar(
                    isScrollable: true,
                    controller: _tabController,
                    tabs:  <Widget>[
                      Tab(text: '兴趣'),
                      Tab(text: '文章'),
                      Tab(text: '活动'),
                    ],
                    indicatorColor: Colors.green,
                    labelColor: QuhuiColors.mainThemeColor,
                    unselectedLabelColor: QuhuiColors.mainTextColor,
                    // add it here
                    indicator: MaterialIndicator(
                      color: QuhuiColors.mainThemeColor,
                      horizontalPadding: 18,
                      paintingStyle: PaintingStyle.fill,
                    ),
                    // labelStyle: QuhuiConstant.smallTextThemeColor,
                    // unselectedLabelStyle: QuhuiConstant.smallText,
                    onTap: (index) {
                      // widget.onPageChanged?.call(index);
                      // _pageController.jumpTo(
                      //     MediaQuery.of(context).size.width * index);
                    }),
              ),
            ),
          ),
        );
      },
    );
  }


  Widget get appBarTitleWidget {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        UserInfoWidget(
          width: 30,
          height: 30,
          image: user?.logo,
        ),Expanded(
          child: Text(
                user?.userName?? '',
                style: QuhuiConstant.smallTextWhite,
              ),
        ),
        // Column(
        //   mainAxisAlignment: MainAxisAlignment.center,
        //   crossAxisAlignment: CrossAxisAlignment.start,
        //   children: [
        //
        //     Text("datassssss", style: QuhuiConstant.minSubText,)
        //   ],
        // ),
      ],
    );
  }

  Widget get appBarBackgroundWidget {
    return Stack(
      children: <Widget>[
        //第一层是背景图
        Container(
            width: double.infinity,
            child: Image.network(
              "https://quhui123.oss-cn-hangzhou.aliyuncs.com/image/user_back.png",
              fit: BoxFit.cover,
            )
        ),
        //第二层是当前主题色的半透明处理
        //第三层是对前两层背景做高斯模糊处理，然后显示上面的内容
        Padding(
          padding: const EdgeInsets.only(left : 8.0),
          child: Container(
            width: double.infinity,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                UserInfoWidget(
                  width: 70,
                  height: 70,
                  image: user.logo,
                ),
                Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      user.userName,
                      style: QuhuiConstant.smallTextWhite,
                    ),
                    // Text("datassssss", style: QuhuiConstant.minSubText,)
                  ],
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }



  @override
  Widget build(BuildContext context) {
    return Observer(
      builder: (_) {
        if(store.UserEntityFuture.status == FutureStatus.fulfilled){
          user = store.UserEntityFuture.result;
          return Scaffold(
            body: NestedScrollView(
                controller: scrollController,

                headerSliverBuilder: (c, s) => [
                  appbar(),
                  //如果不放buttom中
                  // SliverPersistentHeader(
                  //   pinned: true,
                  //   delegate: StickyTabBarDelegate(
                  //     child: PreferredSize(
                  //       preferredSize: const Size.fromHeight(48.0),
                  //       child: Container(
                  //         child: Padding(
                  //           padding: EdgeInsets.fromLTRB(10, 5, 10, 5),
                  //           child: Container(
                  //             width: double.infinity,
                  //             decoration: new BoxDecoration(
                  //               color: QuhuiColors.white, // 底色
                  //               shape: BoxShape.rectangle, // 默认值也是矩形
                  //               borderRadius: new BorderRadius.circular((20.0)), // 圆角度
                  //             ),
                  //             child: new TabBar(
                  //                 isScrollable: true,
                  //                 controller: _tabController,
                  //                 tabs:  <Widget>[
                  //             Tab(text: '兴趣'),
                  //               Tab(text: '文章'),
                  //               Tab(text: '活动'),
                  //               ],
                  //                 labelStyle: TextStyle(
                  //                     color: QuhuiColors.mainThemeColor, fontSize: 14),
                  //                 unselectedLabelStyle: TextStyle(
                  //                     color: QuhuiColors.subTextColor, fontSize: 14),
                  //                 onTap: (index) {
                  //                   // widget.onPageChanged?.call(index);
                  //                   // _pageController.jumpTo(
                  //                   //     MediaQuery.of(context).size.width * index);
                  //                 }),
                  //           ),
                  //         ),
                  //       ),
                  //     ),
                  //   ),
                  // ),
                ],
                body: TabBarView(
                  controller: this._tabController,
                  children: getPageView(),
                )),
          );
        }else{

          return new Scaffold(
            body: Container(
              color: QuhuiColors.white,
              child: Center(
                child: Loading(indicator: BallBeatIndicator(), size: 20.0, color: QuhuiColors.mainThemeColor),
              ),
            ),
          );

        }
      },
    );
  }

  getPageView() {

    List<Widget> tabPageView = new List();

    tabPageView.add(new InterestSimpleListWidgetPage(userId: widget.userId));
    tabPageView.add(new PostSimpleListWidgetPage(userId: widget.userId,));
    tabPageView.add(new ActivitySimpleListWidgetPage(userId: widget.userId,));
    return tabPageView;
  }
}

// class StickyTabBarDelegate extends SliverPersistentHeaderDelegate {
//   final PreferredSizeWidget child;
//
//   StickyTabBarDelegate({@required this.child});
//
//   @override
//   Widget build(
//       BuildContext context, double shrinkOffset, bool overlapsContent) {
//     return Container(
//       color: Theme.of(context).backgroundColor,
//       child: this.child,
//     );
//   }
//
//   @override
//   double get maxExtent => this.child.preferredSize.height;
//
//   @override
//   double get minExtent => this.child.preferredSize.height;
//
//   @override
//   bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
//     return true;
//   }
// }
